package ru.jexp.rcp.supply.swtext;

import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;

import ru.jexp.mvc.HandlerMap;
import ru.jexp.mvc.IListener;
import ru.jexp.rcp.supply.img.JExpImageLink;
import ru.jexp.rcp.supply.swtext.factory.JExpControlFactory;

public class LookupFieldView implements LookupField.IView
{
	public static LookupFieldView createWithTool(Composite parent, String label)
	{
		ToolItem f_tool = JExpControlFactory.createToolButton(parent, label);
		f_tool.setImage(JExpImageLink.getImage(JExpImageLink.LOOKUP));
		final LookupFieldView fieldView = new LookupFieldView(parent, f_tool);
		f_tool.addSelectionListener(new SelectionAdapter()
		{
			public void widgetSelected(SelectionEvent e)
			{
				fieldView.handlers.handle(LOOKUP);
			};
		});
		return fieldView;
	}
	
	
	public static LookupFieldView createWithHyperLink(FormToolkit ft, Composite parent, String label)
	{
		Hyperlink hl = ft.createHyperlink(parent, label, SWT.NONE);
		final LookupFieldView fieldView = new LookupFieldView(parent, hl);
		hl.addHyperlinkListener(new HyperlinkAdapter()
		{
			@Override
			public void linkActivated(HyperlinkEvent e)
			{
				fieldView.handlers.handle(LOOKUP);
			}
		});
		return fieldView;
	}
	
	private IObservableValue text;
	private ISWTObservableValue textEditable;
	private HandlerMap handlers = new HandlerMap();
	private Widget label;

	private LookupFieldView(Composite parent, Widget label)
	{
		this.label = label;
		Text f_text = new Text(parent, SWT.BORDER);
		text = SWTObservables.observeText(f_text, SWT.Modify);
		textEditable = SWTObservables.observeEditable(f_text);
	}

	@Override
	public IObservableValue getText()
	{
		return text;
	}
	
	@Override
	public IObservableValue getTextEditable()
	{
		return textEditable;
	}
	
	public void setLayoutData(Object layoutData)
	{
		getWidgetText().setLayoutData(layoutData);
	}

	public void setEditable(boolean editable)
	{
		getWidgetText().setEditable(editable);
	}
	
	private Text getWidgetText()
	{
		return ((Text)((ISWTObservableValue)getText()).getWidget());
	}

	protected Widget getLabel()
	{
		return label;
	}

	@Override
	public void addLookupHandler(IListener listener)
	{
		handlers.put(LOOKUP, listener);
	}
}
